package me.jessyan.mvparms.demo.mvp.model.logic.api;


import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.speech.tts.TextToSpeech;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;


import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import me.jessyan.mvparms.demo.mvp.ui.activity.CertificateUtils;
import me.jessyan.mvparms.demo.mvp.ui.activity.MainActivity;
import me.jessyan.mvparms.demo.util.SpeechUtils;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class OkHttpUtils {
    private Context mContext;

    //同步get
    public void getSyn(final String url,OkHttpCallBackListener listener) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //创建OkHttpClient对象
                    OkHttpClient client = new OkHttpClient();
                    //创建Request
                    Request request = new Request.Builder()
                            .url(url)//访问连接
                            .get()
                            .build();
                    //创建Call对象
                    Call call = client.newCall(request);
                    //通过execute()方法获得请求响应的Response对象
                    Response response = call.execute();
                    if (response.isSuccessful()) {
                        //处理网络请求的响应，处理UI需要在UI线程中处理
                        //...
                        listener.onSuccess(response.body().string());
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    //异步get
    public void getAsyn(String url,OkHttpCallBackListener listener) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
                listener.onFail(call.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if(response.isSuccessful()){
                    String result = response.body().string();
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder().url(url).build();
                    Call call1 = client.newCall(request);
                    call1.enqueue(new Callback() {

                        @Override
                        public void onFailure(Call call, IOException e) {
                            listener.onFail(call.toString());
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            if(response.isSuccessful()){
                                String result = response.body().string();
                                listener.onSuccess(result);
//                                getAsyn("https://api.map.baidu.com/traffic/v1/road?road_name=杨庄南路&city=北京市&ak=A8fMBlXGIgVC13CZIbIEjGRijAjhxX0t");
                            }
                        }
                    });
                }
            }
        });
    }

    //post
    public void post(String url,String key,String value){
        OkHttpClient client = new OkHttpClient();
        FormBody body = new FormBody.Builder()
                .add(key,value)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //...
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if(response.isSuccessful()){
                    String result = response.body().string();
                    //处理UI需要切换到UI线程处理
                }
            }
        });
    }

    Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what == 200){
                Toast.makeText(mContext,"指令发送成功",Toast.LENGTH_SHORT).show();
            }else{
                Toast.makeText(mContext,"指令发送失败",Toast.LENGTH_SHORT).show();
            }
        }
    };

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public void postForTV(Context mContext,String operate){
        this.mContext = mContext;
        String url = "http://xs.xshuai.com/hcloud/api/tvCommand";
        OkHttpClient client = new OkHttpClient();
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        Map<String,String> parameters = new HashMap<>();
        parameters.put("operate",operate);
        RequestBody requestBody = RequestBody.create(JSON, parameters.toString());
        // Body

        String params = parameters.toString();
        HashMap<String,String> hashMap = new Gson().fromJson(params, new TypeToken<HashMap<String,String>>(){}.getType());
        String timestamp = String.valueOf(System.currentTimeMillis());
        String hotelId = "0831a1ed3c004ff4aad7eaaf93864d80";
        String secretKey = "4396a121f631e4fa999b90b9";
        String roomName = "ceshi";
        String sign = CertificateUtils.createSign(hashMap, hotelId, secretKey, timestamp);
        Map<String,String> header = new HashMap<>();
        header.put("hotelId",hotelId);
        header.put("timestamp",timestamp);
        header.put("sign",sign);
        header.put("roomName",roomName);
        Headers headers = Headers.of(header);
        Request request = new Request.Builder()
                .url(url)
                .headers(headers)
                .post(requestBody)
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i("lzd","err:"+e.toString());
                mHandler.sendEmptyMessage(0);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if(response.isSuccessful()){
                    String result = response.body().string();
                    //处理UI需要切换到UI线程处理
                    Log.i("lzd",result);
                    mHandler.sendEmptyMessage(200);
                }
            }
        });
    }

    public void uploadFile(String url, File file) {
//        OkHttpClient client = new OkHttpClient();
//        RequestBody body =  RequestBody.create(MediaType.get("application/octet-stream"), file);
//        Request request = new Request.Builder()
//                .url(url)
//                .post(body)
//                .build();
//        Call call = client.newCall(request);
        //call.enqueue();
        //...
    }

    public interface OkHttpCallBackListener{
        void onSuccess(String result);
        void onFail(String result);
    }
}
